import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_massage/common_lib/extension/ex_widget.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/generated/assets.dart';
import 'package:flutter_massage/pages/my/address/address_bean.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/sqlite/db_manager.dart';
import 'package:flutter_massage/values/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class EditAddressPage extends GetView<EditAddressLogic> {
  const EditAddressPage({super.key, this.addressBean});

  final AddressBean? addressBean;

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      titleStr: addressBean != null ? '编辑地址' : '新增地址',
      resizeToAvoidBottomInset: false,
      child: GetBuilder<EditAddressLogic>(
        assignId: true,
        init: EditAddressLogic(addressBean: addressBean),
        builder: (logic) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildItem('联系人', '请填写联系人姓名', logic.nameController),
              _buildSex(),
              _buildItem('手机号码', '请填写手机号码', logic.phoneController),
              _buildItem('服务地址', '请输入具体的服务地址', logic.addressController),
              const Spacer(),
              _buildSaveBtn().paddingBottom(ScreenUtil().bottomBarHeight),
            ],
          );
        },
      ),
    );
  }

  Widget _buildSaveBtn() {
    return ButtonWidget.text(
      '保存',
      fontSize: 17,
      textColor: AppColors.white,
      fontWeight: FontWeight.bold,
      alignment: Alignment.center,
      hasInkWell: false,
      gradient: CommonDecoration.xydGradient,
      height: 50.w,
      borderRadius: 50.w,
      onTap: controller.onSave,
    ).paddingHorizontal(12.w);
  }

  Widget _buildSex() {
    return Row(
      children: [
        const TextWidget.oneLine(text: '性别', fontSize: 14, color: AppColors.textLevelTwo).width(100.w),
        Expanded(
          child: Row(
            children: [
              ButtonWidget.iconText(
                (controller.gender == '男' ? Assets.svgRadioSelect : Assets.svgRadioNormal).toSvg(width: 18.w),
                '先生',
                onTap: () {
                  controller.gender = '男';
                  controller.update();
                },
                fontSize: 13,
                textColor: AppColors.textLevelOne,
                hasInkWell: false,
              ),
              ButtonWidget.iconText(
                (controller.gender == '女' ? Assets.svgRadioSelect : Assets.svgRadioNormal).toSvg(width: 18.w),
                '女士',
                onTap: () {
                  controller.gender = '女';
                  controller.update();
                },
                fontSize: 13,
                textColor: AppColors.textLevelOne,
                hasInkWell: false,
              ).paddingLeft(32.w),
            ],
          ),
        ),
      ],
    ).height(54.w).paddingSymmetric(horizontal: 12.w);
  }

  Widget _buildItem(String title, String hint, TextEditingController controller) {
    return Row(
      children: [
        TextWidget.oneLine(text: title, fontSize: 14, color: AppColors.textLevelTwo).width(100.w),
        Expanded(
          child: TextField(
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: hint,
              hintStyle: TextStyle(fontSize: 14, color: '#CCCCCC'.toColor),
            ),
            cursorColor: AppColors.primaryGreen,
            controller: controller,
            keyboardType: title.contains('手机') ? TextInputType.phone : null,
            style: const TextStyle(fontSize: 14, color: AppColors.textLevelOne),
            inputFormatters: title.contains('手机')
                ? <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly,
                    LengthLimitingTextInputFormatter(11),
                  ]
                : null,
          ),
        ),
      ],
    ).height(54.w).paddingSymmetric(horizontal: 12.w);
  }
}

class EditAddressLogic extends GetxController {
  EditAddressLogic({this.addressBean});

  static const String keyListener = 'key_listener_edit_address';

  final AddressBean? addressBean;

  final TextEditingController nameController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController addressController = TextEditingController();
  String gender = '男';

  @override
  void onReady() {
    super.onReady();
    if (addressBean != null) {
      nameController.text = addressBean!.name ?? '';
      phoneController.text = addressBean!.phone ?? '';
      addressController.text = addressBean!.address ?? '';
      gender = addressBean!.gender ?? '男';
    }
  }

  void onSave() async {
    if (Loading.predicate(() => nameController.text.empty, '请填写联系人姓名')) return;
    if (Loading.predicate(() => gender.empty, '请选择性别')) return;
    if (Loading.predicate(() => phoneController.text.length != 11, '请填写正确的手机号码')) return;
    if (Loading.predicate(() => addressController.text.empty, '请输入具体的服务地址')) return;

    if (addressBean == null) {
      ///新增地址
      AddressBean bean = AddressBean(
        name: nameController.text,
        gender: gender,
        phone: phoneController.text,
        address: addressController.text,
        addressId: XydUserService.customId,
      );
      Loading.show();
      await DbManager.addAddress(bean);
      Loading.toast('添加成功', dismissLoading: true);
      CommonRoute.close();
    } else {
      AddressBean bean = AddressBean(
        name: nameController.text,
        gender: gender,
        phone: phoneController.text,
        address: addressController.text,
        addressId: addressBean!.addressId,
      );
      Loading.show();
      await DbManager.editAddress(bean);
      Loading.toast('修改成功', dismissLoading: true);
      CommonRoute.close();
    }

    CommonObservable().publishChange(keyListener);
  }
}
